

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/avatar.gif">
  <link rel="icon" href="/img/avatar.gif">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="马振东">
  <meta name="keywords" content="Java,计算机,数据结构">
  
    <meta name="description" content="一、计算机底层概念1、进程是什么？ 进程是资源分配的基本单位2、线程是什么？ 线程是程序执行的基本单位">
<meta property="og:type" content="article">
<meta property="og:title" content="Java—面向面试">
<meta property="og:url" content="https://bolg.plumdong.top/2020/10/29/Java%E2%80%94%E9%9D%A2%E5%90%91%E9%9D%A2%E8%AF%95/index.html">
<meta property="og:site_name" content="PlumDong Bolg">
<meta property="og:description" content="一、计算机底层概念1、进程是什么？ 进程是资源分配的基本单位2、线程是什么？ 线程是程序执行的基本单位">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/20201028211136787.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/202011020945.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/20201101190805587.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/20201101193300930.png">
<meta property="article:published_time" content="2020-10-29T10:26:13.000Z">
<meta property="article:modified_time" content="2023-03-13T06:57:46.552Z">
<meta property="article:author" content="马振东">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://bolg.plumdong.top/myimages/20201028211136787.png">
  
  
  
  <title>Java—面向面试 - PlumDong Bolg</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"bolg.plumdong.top","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="PlumDong Bolg" type="application/atom+xml">
</head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 60vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>PlumDong Bolg</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Java—面向面试"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2020-10-29 18:26" pubdate>
          2020年10月29日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          33 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Java—面向面试</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="一、计算机底层概念"><a href="#一、计算机底层概念" class="headerlink" title="一、计算机底层概念"></a>一、计算机底层概念</h1><h2 id="1、进程是什么？"><a href="#1、进程是什么？" class="headerlink" title="1、进程是什么？"></a>1、进程是什么？</h2><ul>
<li>进程是资源分配的基本单位<h2 id="2、线程是什么？"><a href="#2、线程是什么？" class="headerlink" title="2、线程是什么？"></a>2、线程是什么？</h2></li>
<li>线程是程序执行的基本单位<span id="more"></span>
<h2 id="3、程序如何开始运行"><a href="#3、程序如何开始运行" class="headerlink" title="3、程序如何开始运行"></a>3、程序如何开始运行</h2></li>
<li>CPU从PC中读指令（PC程序计数器），然后从内存中读数据放在寄存器中，通过ALU计算，最后把结果写入内存并读下一条指令。<h2 id="4、协程与线程"><a href="#4、协程与线程" class="headerlink" title="4、协程与线程"></a>4、协程与线程</h2></li>
<li>协程和线程数不是一一对应，一般协程数要远大于线程。协程更像是一个个在队列中的任务，交由适量线程一个个执行，因此协程数量再多也不会影响CPU效率。而线程数目过多会导致CPU花费在线程调度的时间大幅上升，导致CPU效率降低甚至程序崩溃。<h2 id="5、计算机中的四核八线程原理"><a href="#5、计算机中的四核八线程原理" class="headerlink" title="5、计算机中的四核八线程原理"></a>5、计算机中的四核八线程原理</h2></li>
</ul>
<ul>
<li>CPU中主要包含：计算单元 ALU、寄存器、程序计数器 PC、缓存 chche</li>
<li>一个ALU对应一组寄存器可以执行一个线程</li>
<li>一个ALU对应两组寄存器可以执行两个线程</li>
<li>一个ALU就是一核，对应两组寄存器就是两线程。</li>
</ul>
<h1 id="二、锁"><a href="#二、锁" class="headerlink" title="二、锁"></a>二、锁</h1><h2 id="1、Java中sleep-和wait-的区别"><a href="#1、Java中sleep-和wait-的区别" class="headerlink" title="1、Java中sleep()和wait()的区别"></a>1、Java中sleep()和wait()的区别</h2><ol>
<li><p>最主要是sleep方法没有释放锁，而wait方法释放了锁。sleep不出让系统资源；wait是进入线程等待池等待，出让系统资源。</p>
</li>
<li><p>这两个方法来自不同的类分别是，sleep来自Thread类，和wait来自Object类。sleep()是Thread的静态类方法，在a线程里调用了b的sleep方法，实际上还是a去睡觉。</p>
</li>
<li><p>使用范围：wait，notify和notifyAll只能在同步控制方法或者同步控制块里面使用，而sleep可以在任何地方使用.</p>
</li>
<li><p>sleep必须捕获异常，而wait，notify和notifyAll不需要捕获异常</p>
</li>
</ol>
<h2 id="2、synchronized修饰方法"><a href="#2、synchronized修饰方法" class="headerlink" title="2、synchronized修饰方法"></a>2、synchronized修饰方法</h2><p><strong>1.修饰普通函数：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">()</span></span>&#123;&#125;<br></code></pre></td></tr></table></figure>
<p>等价于</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">()</span></span>&#123;<br>   <span class="hljs-keyword">synchronized</span>(<span class="hljs-keyword">this</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<p><strong>2.修饰静态函数：（Demo是类名）</strong>*</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">()</span></span>&#123;&#125;<br></code></pre></td></tr></table></figure>
<p>等价于</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">()</span></span>&#123;<span class="hljs-keyword">synchronized</span>(Demo.class);&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3、轻量级锁与重量级锁"><a href="#3、轻量级锁与重量级锁" class="headerlink" title="3、轻量级锁与重量级锁"></a>3、轻量级锁与重量级锁</h2><p><strong>1.两者比较</strong></p>
<ul>
<li>轻量级锁不进入等待队列，执行时不需要唤醒，效率高</li>
<li>重量级锁需要进入等待队列，执行时需要系统唤醒，需要耗费时间</li>
</ul>
<p><strong>2.使用策略</strong></p>
<ul>
<li>当竞争不激烈时，每个线程等待时间很短，此时应该选用轻量锁</li>
<li>当竞争非常激烈，线程需要等待很长时间才会执行，此时应使用重量级锁，使用轻量锁会导致CPU浪费。</li>
</ul>
<h2 id="4-volatile-使用"><a href="#4-volatile-使用" class="headerlink" title="4. volatile 使用"></a>4. volatile 使用</h2><ul>
<li>volatile只能保证变量在多线程中可见性，无法保证原子性。</li>
</ul>
<h2 id="5-自旋锁中的CAS方法"><a href="#5-自旋锁中的CAS方法" class="headerlink" title="5. 自旋锁中的CAS方法"></a>5. 自旋锁中的CAS方法</h2><p><strong>1.原理</strong></p>
<ul>
<li>要修改一个变量数值时：假如要把变量m的数值由1加上4，</li>
<li>首先记录变量m当前的值0，然后调用对变量修改的函数加上4，修改完成后比较此时变量m是否还是0，</li>
<li>如果还是0，则把变量m改为新值5，结束。</li>
<li>如果不是0，则重新记录m的当前值，循环执行直至变量没有被其他线程修改。</li>
</ul>
<p><strong>2.CAS方法存在的ABA问题</strong></p>
<ul>
<li>ABA问题是指一个变量被其他线程修改后由改回原先值的问题，是针对于上述CAS的原理中存在的问题。</li>
<li>解决方法：添加版本号，每次被其他线程调用版本号改变。</li>
</ul>
<p><strong>3.CAS方法存在的原子性问题</strong></p>
<ul>
<li>如果变量在CAS判断相同后和赋值前，抢先对其修改了，则CAS方法就失效了。</li>
<li>因此应该在这里保证原子性</li>
<li>解决方法：底层汇编代码使用<code>lock</code>指令锁住总线，其他指定无法执行。</li>
</ul>
<h2 id="6-synchronized锁升级过程"><a href="#6-synchronized锁升级过程" class="headerlink" title="6. synchronized锁升级过程"></a>6. synchronized锁升级过程</h2><p><strong>1.升级过程</strong><br>偏向锁 —&gt; 轻量锁 —&gt; 重量锁<br><img src="/myimages/20201028211136787.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><strong>2.偏向锁</strong></p>
<ul>
<li>偏向锁是一种无锁状态，即线程声明这把锁是自己的即可，不用需要竞争，因为大部分的代码是单线程执行的，这样会大幅节省时间。</li>
<li>升级时机：只要有一个线程来抢锁，就必须升级为轻量级锁。</li>
</ul>
<p><strong>3.轻量级锁</strong></p>
<ul>
<li>轻量级锁用于多线程竞争比激烈的情况，此时没有获得锁的线程不会进入阻塞状态，会在原地等待或者尝试获得锁</li>
<li>如果等待的线程过多或等待时间过长，就会升级为重量级锁.</li>
</ul>
<p><strong>4.重量级锁</strong></p>
<ul>
<li>没有获得锁的线程会自动进入阻塞状态，当有线程释放锁时会唤醒线程来竞争</li>
<li>线程进入阻塞状态或者唤醒线程时cpu会切换到内核态执行，会消耗一定的cpu资源.</li>
</ul>
<h2 id="7-Object-o-new-Object-发生了什么"><a href="#7-Object-o-new-Object-发生了什么" class="headerlink" title="7. Object o = new Object();发生了什么"></a>7. Object o = new Object();发生了什么</h2><ul>
<li>这个问题好像就是问：把大象装冰箱需要几步，1把冰箱门打开，2把大象装进去，3把冰箱门关上。</li>
<li>编译器执行时也分三步：</li>
</ul>
<blockquote>
<p>1.申请一个内存空间，变量都是默认值，基础变量是0，引用变量是null。<br>2.调用构造方法，对变量进行初始化。<br>3.建立对象与其引用的联系。</p>
</blockquote>
<h2 id="8-简单的单例类"><a href="#8-简单的单例类" class="headerlink" title="8. 简单的单例类"></a>8. 简单的单例类</h2><ul>
<li><strong>写法一：加载时创建</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Mgr01</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Mgr01 INSTANCE = <span class="hljs-keyword">new</span> Mgr01();<br>    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Mgr01</span><span class="hljs-params">()</span></span>&#123;&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Mgr01 <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123; <span class="hljs-keyword">return</span> INSTANCE;&#125;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">m</span><span class="hljs-params">()</span></span>&#123; System.out.println(<span class="hljs-string">&quot;m&quot;</span>);&#125;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        Mgr01 m1 = Mgr01.getInstance();<br>        Mgr01 m2 = Mgr01.getInstance();<br>        System.out.println(m1 == m2);<br>    &#125;<br>&#125; <br></code></pre></td></tr></table></figure></li>
<li><strong>写法二：使用时创建该类的对象</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Mgr01</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Mgr01 INSTANCE;<br>    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Mgr01</span><span class="hljs-params">()</span></span>&#123;&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Mgr01 <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123; <br>        <span class="hljs-keyword">if</span>(INSTANCE == <span class="hljs-keyword">null</span>)&#123;<br>             INSTANCE = <span class="hljs-keyword">new</span> Mgr01();<br>        &#125;<br>        <span class="hljs-keyword">return</span> INSTANCE;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><strong>写法三DCL（Double Check Lock）单例模式</strong>：采用锁双重验证锁机制，保证线程安全。同时降低锁粒度提高并发效率。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Mgr01</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">volatile</span> Mgr01 INSTANCE;<br>    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Mgr01</span><span class="hljs-params">()</span></span>&#123;&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Mgr01 <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;<br>        <span class="hljs-comment">//多个业务逻辑</span><br>        <span class="hljs-keyword">if</span>(INSTANCE == <span class="hljs-keyword">null</span>)&#123;<br>            <span class="hljs-keyword">synchronized</span> (Mgr01.class) &#123;<br>                <span class="hljs-keyword">if</span>(INSTANCE == <span class="hljs-keyword">null</span>) &#123;<br>                    <span class="hljs-comment">//多个业务</span><br>                    INSTANCE = <span class="hljs-keyword">new</span> Mgr01();<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> INSTANCE;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><strong>DCL单例模式需要加volatile修饰吗？答案：必须加！</strong><blockquote>
<p><strong>1.原因分析：</strong> 采用DCL方法创建单例模式时，若不加<strong>volatile</strong>修饰<strong>INSTANCE</strong>变量CPU在执行时会对指令或语句进行重排序。就会存在这样的情况：<br><strong>2.特殊情况：</strong> 线程1获得锁在new一个相应的单例对象，分三步1：申请空间2：变量赋值3：<strong>INSTANCE</strong>指向内存空间。CPU优化指令把第2步与第3步顺序交换，就会导致提前返回一个未完全初始的对象。此时恰好轮到线程2执行，线程2将判断<strong>INSTANCE</strong>是否是空，由于线程1已经将其指向相应的内存，就会导致<strong>INSTANCE</strong>非空，函数就会返回一个未完全初始化的对象。。<br><strong>3.解决办法：</strong> 使用<strong>volatile</strong>修饰则可避免CPU在执行时对其重排序问题。</p>
</blockquote>
</li>
</ul>
<h2 id="9-JVM内存屏障"><a href="#9-JVM内存屏障" class="headerlink" title="9.JVM内存屏障"></a>9.JVM内存屏障</h2><p><strong>屏障两边的指令不可以重排，保障有序。</strong></p>
<ul>
<li><strong>hotspot实现方式</strong><br>汇编层通<strong>LOCK</strong>执行一条空语句实现</li>
</ul>
<p><strong>LOCK用于在多处理器中执行命令时对共享内存的独占使用。<br>它的作用是能够将当前处理器对应缓存的内容刷新到内存中，并使其他处理器对应的缓存失效。另外还提供了有序的指令无法越过这个内存屏障的作用。</strong></p>
<h1 id="三、JVM-GC（Garbage-Collector）"><a href="#三、JVM-GC（Garbage-Collector）" class="headerlink" title="三、JVM GC（Garbage Collector）"></a>三、JVM GC（Garbage Collector）</h1><h2 id="1-怎么判断一块内存是垃圾："><a href="#1-怎么判断一块内存是垃圾：" class="headerlink" title="1.怎么判断一块内存是垃圾："></a><strong>1.怎么判断一块内存是垃圾：</strong></h2><p>Root Searching算法：从ROOT根上开始找，凡是能找到的就不是垃圾，否则就清除。</p>
<h2 id="2-三种垃圾回收算法："><a href="#2-三种垃圾回收算法：" class="headerlink" title="2.三种垃圾回收算法："></a><strong>2.三种垃圾回收算法：</strong></h2><p><strong>Mark-Sweep(标记清除)、Copying(拷贝)、Mark-Compact(标记压缩)</strong></p>
<ul>
<li><strong>标记清除</strong>：把可回收的对象标记为未使用的，缺点会差生大量碎片</li>
<li><strong>拷贝</strong>：把内存一分为二，把存活对象复制到另一半，然后把前一半内存全部清除。缺点内存浪费</li>
<li><strong>标记压缩</strong>：标记清楚后，把存活的对象压缩到连续的内存空间。缺点效率低</li>
</ul>
<h2 id="3-Garbage-Collector的十种垃圾回收器："><a href="#3-Garbage-Collector的十种垃圾回收器：" class="headerlink" title="3.Garbage Collector的十种垃圾回收器："></a><strong>3.Garbage Collector的十种垃圾回收器：</strong></h2><p><img src="/myimages/202011020945.png" srcset="/img/loading.gif" lazyload alt="十种垃圾回收器"><br><strong>JDK1.8默认垃圾回收器(PS + PO)</strong><br>垃圾回收器分为两种——分代模型和分区模型</p>
<ul>
<li><strong>分代模型：</strong><br>分为新生代和老年代。原理：新生代存放新new出来的对象，老年代存放多次清理未清理掉的对象，新生代区域采用Copying(拷贝)回收算法，老年代采用Mark-Sweep或者Mark-Compact回收算法。<br><img src="/myimages/20201101190805587.png" srcset="/img/loading.gif" lazyload alt="分代模型"></li>
<li><strong>分代模型中对象创建过程</strong><br>对象在创建时第一步会检测对象能否创建在栈上（逃逸分析和标量替换）如果能则直接创建在栈上，如果不能则放在堆上：对象比较大直接放在老年代（因为老年代分区大）较小则放在新生代，在新生代中多次回收后没回收的对象转移到老年代。<br><img src="/myimages/20201101193300930.png" srcset="/img/loading.gif" lazyload alt="分代模型"></li>
</ul>
<h2 id="4-STW现象"><a href="#4-STW现象" class="headerlink" title="4.STW现象"></a>4.STW现象</h2><p> <strong>STW全称stop-the-world（世界停止），原因：垃圾回收器开始工作，所有业务必须停止等待，在JVM调优时应极力缩短STW现象的时间。</strong></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Java%E5%9F%BA%E7%A1%80/" class="category-chain-item">Java基础</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Java/">#Java</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Java—面向面试</div>
      <div>https://bolg.plumdong.top/2020/10/29/Java—面向面试/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>马振东</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2020年10月29日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/11/02/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0/" title="深入理解Java线程池">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">深入理解Java线程池</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/10/28/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/" title="设计模式-观察者模式">
                        <span class="hidden-mobile">设计模式-观察者模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
